package com.shenjinzheng.movie_ticket_app.repository


import com.shenjinzheng.movie_ticket_app.network.ApiService
import com.shenjinzheng.movie_ticket_app.network.RetrofitClient
import com.shenjinzheng.movie_ticket_app.model.Movie
import com.shenjinzheng.movie_ticket_app.network.MovieResponse
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import retrofit2.Response

class MovieRepository(private val apiService: ApiService) {

    // 从网络获取电影数据（分页）
    suspend fun getPopularMovies(apiKey: String, page: Int): Result<List<Movie>> {
        return try {
            val response = apiService.getPopularMovies(apiKey, page.toString())

            if (response.isSuccessful) {
                response.body()?.let {
                    Result.success(it.movies)  // 返回成功的电影列表
                } ?: Result.failure(Exception("空的响应数据"))
            } else {
                Result.failure(Exception("请求失败: ${response.code()}"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    // 在 MovieRepository 中添加搜索函数
    suspend fun searchMovies(apiKey: String, query: String): Result<List<Movie>> {
        return try {
            val response = apiService.searchMovies(apiKey, query)

            if (response.isSuccessful) {
                response.body()?.let {
                    Result.success(it.movies)
                } ?: Result.failure(Exception("空的响应数据"))
            } else {
                Result.failure(Exception("请求失败: ${response.code()}"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }
}
